package aip.core.dao.message;

import java.util.Date;
import java.util.List;

import org.springframework.dao.DataAccessException;

import aip.core.model.message.Message;
import aip.ui.user.util.UserHelper;

import com.googlecode.horncomb.bean.filter.ConditionSet;
import com.googlecode.horncomb.bean.filter.SimpleMapConditionSet;
import com.googlecode.horncomb.bean.order.DefaultOrder;
import com.googlecode.horncomb.bean.order.DefaultOrderToken;
import com.googlecode.horncomb.bean.order.Order;
import com.googlecode.horncomb.bean.paged.PagedList;
import com.googlecode.horncomb.orm.ibatis.SqlMapEntityDaoImpl;

/**
 * Message data access object
 * <p>
 * 负责人/principal:<br/>
 * 修改记录/revision:<br/>
 * 日期:<br/>
 * 修改人:<br/>
 * 修改说明:<br/>
 * @author
 * @version $Id$
 */
public class MessageDao extends SqlMapEntityDaoImpl<Message>
{
    private static final long serialVersionUID = -278850820614280478L;

    /**
     * {@inheritDoc}
     */
    @Override
    public void insert(Message entity) throws DataAccessException
    {
        // TODO 当前用户
        if (UserHelper.getUser() != null)
        {
            entity.setSubmiter(UserHelper.getUser().getUsername());
        }
        entity.setState(Message.STATE_ASIGNED);
        entity.setSubmitTime(new Date());
        super.insert(entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void update(Message entity) throws DataAccessException
    {
        Date now = new Date();
        entity.setState(Message.STATE_REPLIED);
        entity.setReplyTime(now);
        if (UserHelper.getUser() != null)
        {
            entity.setExpert(UserHelper.getUser().getUsername());
        }
        super.update(entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public PagedList<List<? extends Message>> query(ConditionSet constraints,
            Order order, int page, int pageSize) throws DataAccessException
    {
        return super.query(constraints, order, page, pageSize);
    }

    public List<? extends Message> queryListByType(String expert, String state,
            int start, int pageSize) throws DataAccessException
    {
        ConditionSet cons = new SimpleMapConditionSet().addConstraint("state",
                state);
        Order order = new DefaultOrder(
                new DefaultOrderToken("RE_TIME_", false),
                new DefaultOrderToken("SUBMIT_TIME_", false));
        return this.query(cons, order, start, pageSize).getSource();
    }

    public int getDataCount(String expert, String state)
    {
        ConditionSet constraints = new SimpleMapConditionSet().addConstraint(
                "expert", expert).addConstraint("state", state);
        return super.queryCount(constraints);
    }
}
